package com.example.medicalequipment.controller;

import android.content.Context;
import android.os.AsyncTask;

import com.example.medicalequipment.database.AppDatabase;
import com.example.medicalequipment.entity.MedicalDevice;

import java.util.List;

public class RepairController {
    private AppDatabase database;
    private OnRepairSubmitListener listener;

    public RepairController(Context context, OnRepairSubmitListener listener) {
        this.database = AppDatabase.getInstance(context);
        this.listener = listener;
    }

    // 获取所有维修申请
    public List<MedicalDevice> getAllRepairRequests() {
        return database.medicalDeviceDao().getAllDevices();
    }

    // 根据ID获取维修申请
    public MedicalDevice getRepairRequestById(int deviceId) {
        return database.medicalDeviceDao().getDeviceById(deviceId);
    }

    // 更新维修申请状态
    public void updateRepairStatus(MedicalDevice device, OnUpdateListener listener) {
        new UpdateStatusTask(listener).execute(device);
    }

    private class UpdateStatusTask extends AsyncTask<MedicalDevice, Void, Boolean> {
        private OnUpdateListener listener;

        public UpdateStatusTask(OnUpdateListener listener) {
            this.listener = listener;
        }

        @Override
        protected Boolean doInBackground(MedicalDevice... devices) {
            try {
                // 这里需要在DAO中添加update方法
                database.medicalDeviceDao().updateDevice(devices[0]);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (listener != null) {
                listener.onUpdate(success);
            }
        }
    }

    // 新增：更新状态回调接口
    public interface OnUpdateListener {
        void onUpdate(boolean success);
    }


    public void submitRepairRequest(MedicalDevice device) {
        new InsertDeviceTask().execute(device);
    }

    private class InsertDeviceTask extends AsyncTask<MedicalDevice, Void, Long> {
        @Override
        protected Long doInBackground(MedicalDevice... devices) {
            try {
                return database.medicalDeviceDao().insertDevice(devices[0]);
            } catch (Exception e) {
                e.printStackTrace();
                return -1L;
            }
        }

        @Override
        protected void onPostExecute(Long result) {
            if (listener != null) {
                if (result > 0) {
                    listener.onRepairSubmitted(true, "维修申请已提交成功");
                } else {
                    listener.onRepairSubmitted(false, "维修申请提交失败，请重试");
                }
            }
        }
    }

    public interface OnRepairSubmitListener {
        void onRepairSubmitted(boolean success, String message);
    }
}
